package com.javaear.beangenerator;

import com.javaear.beangenerator.tools.Assert;
import com.javaear.beangenerator.tools.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * beaner model
 *
 * @author aooer
 */
public final class Beaner extends ContextHolder {

    /**
     * beanName
     */
    private String beanName;

    /**
     * field List
     */
    private List<Fielder> fieldList;

    /**
     * prefix space
     */
    private String prefixSpace = StringUtils.PREFIX_SPACE;

    /**
     * children Beaner
     */
    private List<Beaner> children = new ArrayList<Beaner>();

    public Beaner(String beanName, List<Fielder> fieldList) {
        this.beanName = beanName;
        this.fieldList = fieldList;
    }

    public Beaner(String beanName, List<Fielder> fieldList, List<Beaner> children) {
        this.children = children;
        this.beanName = beanName;
        this.fieldList = fieldList;
    }

    public String getBeanName() {
        return beanName;
    }

    public String toString() {
        Assert.notEmpty(fieldList);
        boolean isParent = prefixSpace.equals(StringUtils.PREFIX_SPACE);
        boolean hasList = false;
        StringBuilder beanBuilder = new StringBuilder(isParent ? "" : StringUtils.LINE);
        StringBuilder getterSetterBuilder = new StringBuilder();
        beanBuilder.append(prefixSpace.substring(4)).append("public ").append(isParent ? "" : "static ").append("class ").append(StringUtils.upperCaseFirstChar(beanName)).append(" {").append(StringUtils.LINE);
        for (Fielder field : fieldList) {
            field.append(prefixSpace, beanBuilder, getterSetterBuilder);
            if (field.isListFieldType()) hasList = true;
        }
        if (!children.isEmpty() && embedStyle()) {
            for (Beaner child : children) {
                child.prefixSpace = this.prefixSpace.concat(StringUtils.PREFIX_SPACE);
                beanBuilder.append(child);
            }
        }
        beanBuilder.insert(0, classHeadCodeTemplate(isParent, hasList));
        return beanBuilder.append(getterSetterBuilder).append(prefixSpace.substring(4)).append("}\n").toString();
    }

    public List<Beaner> getChildren() {
        return children;
    }
}
